const { pool, data_url } = require('../database.js');

const getFriends = async (request, response) => {
  // 数据库设置了触发器
  // 触发器会自动维护关系类型：
  // 单向关注时：关注方为1，被关注方为2
  // 互相关注时：双方都更新为3（好友）
  // 默认为4（陌生人）
  try {
    const userId = request.query.user_id;

    // 获取好友列表及最后一条消息，并包含关系类型
    const sql = `
      SELECT 
        u.user_id as userId,
        u.author_name as username,
        u.avatar_url as avatar,
        f.relationship_type as type,
        (
          SELECT content 
          FROM chat_messages 
          WHERE (sender_id = f.friend_id AND receiver_id = ?) 
             OR (sender_id = ? AND receiver_id = f.friend_id)
          ORDER BY send_time DESC 
          LIMIT 1
        ) as lastMessage,
        (
          SELECT send_time 
          FROM chat_messages 
          WHERE (sender_id = f.friend_id AND receiver_id = ?) 
             OR (sender_id = ? AND receiver_id = f.friend_id)
          ORDER BY send_time DESC 
          LIMIT 1
        ) as lastTime
      FROM friends f
      JOIN users u ON f.friend_id = u.user_id
      WHERE f.user_id = ?
      ORDER BY lastTime DESC
    `;

    const [friends] = await pool.execute(sql, [
      userId, userId, userId, userId, userId
    ]);

    // 处理结果
    const processedResults = friends.map(result => ({
      ...result,
      avatar: data_url + result.avatar,
      type: result.type || 4  // 如果type为null，默认为4（陌生人）
    }));

    response.json({
      code: 200,
      msg: 'success',
      data: processedResults
    });

  } catch (error) {
    console.error('获取好友列表失败:', error);
    response.json({
      code: 500,
      msg: '服务器错误',
      data: null
    });
  }
}

const getMessages = async (request, response) => {
  try {
    const { user_id, friend_id, page = 1, pageSize = 50 } = request.query;

    // 调试日志
    // console.log('原始请求参数:', request.query);

    // 参数验证
    if (!user_id || !friend_id) {
      console.log('缺少参数:', { user_id, friend_id });
      return response.json({
        code: 400,
        msg: '缺少必要参数 user_id 或 friend_id',
        data: null
      });
    }

    // 使用问号占位符而不是直接使用 LIMIT 和 OFFSET
    const sql = `
      SELECT 
        m.message_id,
        m.sender_id,
        m.receiver_id,
        m.content,
        m.send_time,
        m.is_read,
        u.author_name as username,
        u.avatar_url as avatar
      FROM chat_messages m
      JOIN users u ON m.sender_id = u.user_id
      WHERE (sender_id = ? AND receiver_id = ?)
         OR (sender_id = ? AND receiver_id = ?)
      ORDER BY send_time DESC
      LIMIT ${parseInt(pageSize)} OFFSET ${(parseInt(page) - 1) * parseInt(pageSize)}
    `;

    // 只传递 WHERE 条件的参数
    const params = [
      parseInt(user_id),
      parseInt(friend_id),
      parseInt(friend_id),
      parseInt(user_id)
    ];

    const [messages] = await pool.execute(sql, params);
    // console.log('查询结果数量:', messages.length);

    // 格式化消息数据
    const formattedMessages = messages.map(msg => ({
      message_id: msg.message_id,
      sender_id: msg.sender_id,
      receiver_id: msg.receiver_id,
      content: msg.content,
      send_time: msg.send_time,
      is_read: msg.is_read === 1,
      username: msg.username,
      avatar: msg.avatar ? `${data_url}${msg.avatar}` : null
    }));

    response.json({
      code: 200,
      msg: 'success',
      data: formattedMessages.reverse()
    });

  } catch (error) {
    console.error('获取聊天记录失败:', {
      error: error.message,
      stack: error.stack
    });

    response.json({
      code: 500,
      msg: '服务器错误: ' + error.message,
      data: null
    });
  }
}

const sendMessage = async (request, response) => {
  try {
    const {
      userId,      // 发送者ID
      receiverId,  // 接收者ID
      content,     // 消息内容
      time        // 发送时间
    } = request.body;

    // 参数验证
    if (!userId || !receiverId || !content) {
      return response.json({
        code: 400,
        msg: '缺少必要参数',
        data: null
      });
    }

    // 构建SQL
    const sql = `
      INSERT INTO chat_messages 
      (sender_id, receiver_id, content, send_time, is_read) 
      VALUES (?, ?, ?, ?, 0)
    `;

    // 执行插入
    const [result] = await pool.execute(sql, [
      parseInt(userId),
      parseInt(receiverId),
      content,
      time ? new Date(time) : new Date()
    ]);

    // 获取发送者信息
    const userSql = `
      SELECT user_id, user_account as username, avatar_url as avatar
      FROM users 
      WHERE user_id = ?
    `;
    const [userInfo] = await pool.execute(userSql, [userId]);

    // 返回消息数据
    response.json({
      code: 200,
      msg: 'success',
      data: {
        messageId: result.insertId,
        userId: parseInt(userId),
        receiverId: parseInt(receiverId),
        content,
        sendTime: time || new Date().toISOString(),
        isRead: false,
        username: userInfo[0]?.username,
        avatar: userInfo[0]?.avatar ? `${data_url}${userInfo[0].avatar}` : null
      }
    });

  } catch (error) {
    console.error('发送消息失败:', error);
    response.json({
      code: 500,
      msg: '服务器错误: ' + error.message,
      data: null
    });
  }
}

// 删除好友关系接口
const deleteFriendship = async (request, response) => {
  try {
    const { friend_id } = request.body;
    const user_id = request.query.user_id;

    // 首先查询当前的关系类型
    const checkSql = 'SELECT relationship_type FROM friends WHERE user_id = ? AND friend_id = ?';
    const [relationResult] = await pool.execute(checkSql, [user_id, friend_id]);

    if (relationResult.length === 0) {
      return response.json({
        msg: '关系不存在',
        code: "404"
      });
    }

    const relationship_type = relationResult[0].relationship_type;
    let actionMsg = '';

    // 根据关系类型设置不同的提示信息
    switch (relationship_type) {
      case 1:
        actionMsg = '取消关注';
        break;
      case 2:
        actionMsg = '移除粉丝';
        break;
      case 3:
        actionMsg = '删除好友';
        break;
      case 4:
        actionMsg = '移除';
        break;
      default:
        actionMsg = '删除关系';
    }

    // 开启事务
    const connection = await pool.getConnection();
    try {
      await connection.beginTransaction();

      // 如果是互相关注（好友）状态，需要更新对方的关系为粉丝
      if (relationship_type == 3) {
        const updateOtherSql = `
          UPDATE friends 
          SET relationship_type = 2 
          WHERE user_id = ? AND friend_id = ?
        `;
        await connection.execute(updateOtherSql, [user_id, friend_id]);
        console.log('更新对方关系为粉丝成功');
      } else {
        // 删除关系
        const deleteSql = 'DELETE FROM friends WHERE user_id = ? AND friend_id = ?';
        await connection.execute(deleteSql, [user_id, friend_id]);
        console.log('删除关系成功');
      }

      await connection.commit();

      response.json({
        msg: `${actionMsg}成功`,
        code: "200",
        data: {
          user_id,
          friend_id,
          action: actionMsg
        }
      });

    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }

  } catch (error) {
    console.error('删除关系失败:', error);
    response.json({
      msg: '服务器错误',
      code: "500",
      error: error.message
    });
  }
};

// 关注接口
const followUser = async (request, response) => {
  try {
    const { friend_id } = request.body;
    const user_id = request.query.user_id;

    // 检查是否关注自己
    if (user_id === friend_id) {
      return response.json({
        msg: '不能关注自己',
        code: "400"
      });
    }

    const connection = await pool.getConnection();
    try {
      await connection.beginTransaction();

      // 检查是否已经存在关系
      const checkSql = 'SELECT relationship_type FROM friends WHERE user_id = ? AND friend_id = ?';
      const [existingRelation] = await connection.execute(checkSql, [user_id, friend_id]);

      if (existingRelation.length > 0) {
        await connection.rollback();
        return response.json({
          msg: '已经存在关注关系',
          code: "400"
        });
      }

      // 检查对方是否已经关注了自己
      const checkReverseSql = 'SELECT relationship_type FROM friends WHERE user_id = ? AND friend_id = ?';
      const [reverseRelation] = await connection.execute(checkReverseSql, [friend_id, user_id]);

      let relationship_type = 1; // 默认为关注关系
      let actionMsg = '关注成功';

      if (reverseRelation.length > 0) {
        // 如果对方已经关注了自己，则双方都升级为好友关系
        if (reverseRelation[0].relationship_type === 1 || reverseRelation[0].relationship_type === 2) {
          const updateReverseSql = `
            UPDATE friends 
            SET relationship_type = 3 
            WHERE user_id = ? AND friend_id = ?
          `;
          await connection.execute(updateReverseSql, [friend_id, user_id]);
          relationship_type = 3;
          actionMsg = '已成为好友';
        }
      }

      // 添加关注关系
      const insertSql = `
        INSERT INTO friends (user_id, friend_id, relationship_type) 
        VALUES (?, ?, ?)
      `;
      await connection.execute(insertSql, [user_id, friend_id, relationship_type]);

      await connection.commit();

      response.json({
        msg: actionMsg,
        code: "200",
        data: {
          user_id,
          friend_id,
          relationship_type,
          relationship_name: relationship_type === 1 ? '关注' : '好友'
        }
      });

    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }

  } catch (error) {
    console.error('关注操作失败:', error);
    response.json({
      msg: '服务器错误',
      code: "500",
      error: error.message
    });
  }
};

// 搜索用户接口
const searchUsers = async (request, response) => {
  try {
    const { search } = request.body;
    const user_id = request.query.user_id;

    if (!search) {
      return response.json({
        msg: '搜索内容不能为空',
        code: "400"
      });
    }

    // 搜索用户并判断关系
    const sql = `
      SELECT 
        u.user_id,
        u.author_name,
        u.user_account,
        u.avatar_url,
        EXISTS (
          SELECT 1 
          FROM friends f 
          WHERE f.user_id = ? 
          AND f.friend_id = u.user_id 
          AND f.relationship_type IN (1, 3)
        ) as isrelationship
      FROM users u
      WHERE u.author_name LIKE ?
      AND u.user_id != ?  -- 排除自己
      LIMIT 20           -- 限制返回数量
    `;

    const [users] = await pool.execute(sql, [
      user_id,
      `%${search}%`,
      user_id
    ]);

    // 处理结果
    const processedUsers = users.map(user => ({
      user_id: user.user_id,
      author_name: user.author_name,
      user_account: user.user_account,
      avatar_url: user.avatar_url ? data_url + user.avatar_url : null,
      isrelationship: Boolean(user.isrelationship)
    }));

    response.json({
      msg: 'success',
      code: "200",
      data: processedUsers
    });

  } catch (error) {
    console.error('搜索用户失败:', error);
    response.json({
      msg: '服务器错误',
      code: "500",
      error: error.message
    });
  }
};

module.exports = {
  getFriends,
  getMessages,
  sendMessage,
  deleteFriendship,
  followUser,
  searchUsers
};